package com.wiiss.modeler.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.wiiss.common.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;

@Api(tags = "获取流程数据")
@RestController
@AllArgsConstructor
public class ModelEditorJsonRestResourceController extends BaseController implements ModelDataJsonConstants {

    private static final Logger LOGGER = LoggerFactory.getLogger(ModelEditorJsonRestResourceController.class);

    private RepositoryService repositoryService;
    private ObjectMapper objectMapper;
    @ApiOperation("根据modelId查询")
    @RequestMapping(value = "/modeler/model/{modelId}/json", method = RequestMethod.GET, produces = "application/json")
    public ObjectNode getEditorJson(@PathVariable String modelId) {

        ObjectNode modelNode = null;

        Model model = repositoryService.getModel(modelId);

        if (model != null) {
            try {
                if (StringUtils.isNotEmpty(model.getMetaInfo())) {
                    modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
                } else {
                    modelNode = objectMapper.createObjectNode();
                    modelNode.put(MODEL_NAME, model.getName());
                }
                modelNode.put(MODEL_ID, model.getId());

                byte[] byteArr = repositoryService.getModelEditorSource(model.getId());

                String xml = new String(byteArr, StandardCharsets.UTF_8);

                ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(xml);
                modelNode.put("model", editorJsonNode);

            } catch (Exception e) {
                LOGGER.error("Error creating model JSON", e);
                throw new ActivitiException("Error creating model JSON", e);
            }
        }
        return modelNode;
    }

}
